package ocrV1

import (
	"fmt"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	ocr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr/v20181119"
	"ocr/config"
	"strconv"
)

type GeneralBasic struct {
}

func (gb GeneralBasic) Ocr(input map[string]string) (string, error) {
	//getCredential
	credential := gb.getCredential()
	request := gb.getRequest(input)
	//getRequest
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = config.OcrConfig.GetString("OcrConf.Endpoint")
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := ocr.NewClient(credential, config.OcrConfig.GetString("OcrConf.Region"), cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象

	response, err := client.GeneralBasicOCR(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return "", err
	}
	if err != nil {
		panic(err)
	}
	return gb.getResponse(response), nil
	//getResponse
}

func (*GeneralBasic) getCredential() *common.Credential {
	// 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
	// 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
	return common.NewCredential(
		config.OcrSecret.GetString("OcrSecret.SecretId"),
		config.OcrSecret.GetString("OcrSecret.SecretKey"),
	)
}

func (*GeneralBasic) getRequest(input map[string]string) *ocr.GeneralBasicOCRRequest {
	request := ocr.NewGeneralBasicOCRRequest()
	imageUrl := input["image_url"]
	imageBase64 := input["image_base64"]
	scene := input["scene"]
	languageType := input["languageType"]
	isPdf, _ := strconv.ParseBool(input["is_pdf"])
	pdfPageNumber, _ := strconv.ParseUint(input["pdfPageNumber"], 10, 64)
	isWords, _ := strconv.ParseBool(input["is_words"])

	request.ImageUrl = &imageUrl
	request.ImageBase64 = &imageBase64
	request.Scene = &scene
	request.LanguageType = &languageType
	request.IsPdf = &isPdf
	request.PdfPageNumber = &pdfPageNumber
	request.IsWords = &isWords
	return request
}

func (*GeneralBasic) getResponse(response *ocr.GeneralBasicOCRResponse) string {
	return response.ToJsonString()
}
